package com.example.anquan.config;


import com.example.anquan.Service.UserService;
import com.example.anquan.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import javax.swing.*;

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
//    @Override
//    protected void configure(AuthenticationManagerBuilder auth) throws Exception{
//        BCryptPasswordEncoder encoder=new BCryptPasswordEncoder();
//        auth.inMemoryAuthentication().passwordEncoder(encoder)
//                .withUser("vip").password(encoder.encode("123")).roles("vip")
//                .and()
//                .withUser("张三").password(encoder.encode("123")).roles("common");
//    }
//    @Override
//    protected void configure(HttpSecurity http)throws Exception {
//        http.authorizeRequests()
//                .antMatchers("/index").permitAll()
//                .antMatchers("/common/**").hasRole("common")
//                .antMatchers("/vip/**").hasRole("vip")
//                .anyRequest().authenticated()
//                .and().formLogin()
//                .and().logout()
//                .and().rememberMe();
//    }

    @Override
    protected void configure(HttpSecurity http)throws Exception {
        http.authorizeRequests()
                .antMatchers("/index").permitAll()
                .antMatchers("/common/**").hasRole("common")
                .antMatchers("/vip/**").hasRole("vip")
                .anyRequest().authenticated();
        http.formLogin()
                .loginPage("/login").permitAll()
                .usernameParameter("username").passwordParameter("password")
                .defaultSuccessUrl("/index")
                .failureUrl("/login?error");
        http.logout()
                .logoutUrl("/logout")
                .logoutSuccessUrl("/index");
        http.rememberMe()
                .rememberMeParameter("rememberme")
                .tokenValiditySeconds(200);
    }

@Autowired
private UserService userService;
    @Override
    protected void configure(AuthenticationManagerBuilder auth)throws
            Exception {
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        auth.userDetailsService(userService).passwordEncoder(encoder);
    }
}

